//
//  ZQGoodsOptionView.m
//  shoppingmall
//
//  Created by admin on 2017/9/27.
//  Copyright © 2017年 morplcp. All rights reserved.
//

#import "ZQGoodsOptionView.h"
#import "ZQMainString.h"
#import "ZQBaseCollectionViewLabelCell.h"
#import "UICollectionViewLeftAlignedLayout.h"
#import "SearchHistoryCollectionReusableView.h"

@interface ZQGoodsOptionView() <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, copy) NSArray *options;
@property (nonatomic, strong) ZQGoodsModel *goodsInfo;
@property (nonatomic, strong) ZQBaseBoxView *bgView;
@property (nonatomic, strong) ZQBaseBoxView *contentView;

@property (nonatomic, strong) ZQBaseBoxView *topBox;
@property (nonatomic, strong) ZQBaseBoxView *headerBoxView;
@property (nonatomic, strong) UIImageView *headerImageView;
@property (nonatomic, strong) ZQBaseLabel *priceLabel;
@property (nonatomic, strong) ZQBaseLabel *selectOptionsLabel;
@property (nonatomic, strong) UIButton *closeButton;

@property (nonatomic, strong) UICollectionView *optionsCollectionView;
@property (nonatomic, strong) UIButton *sureButton;

@property (nonatomic, strong) NSMutableDictionary *selectOptions; // 记录所选择的商品类型

@property (nonatomic, copy) void(^optionsBlock)(NSDictionary *options);

@end

@implementation ZQGoodsOptionView

- (instancetype)initWithGoodsInfo:(ZQGoodsModel *)goodsInfo options:(NSString *)options
{
    self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    if (self)
    {
        self.goodsInfo = goodsInfo;
        self.options = [SYJUtility objectWithJsonStr:options];
        [self initSubViews];
        [self setUIData];
    }
    return self;
}

- (void)initSubViews
{
    [self addSubview:self.bgView];
    [self.bgView addSubview:self.contentView];
    [self.contentView addSubview:self.topBox];
    [self.topBox addSubview:self.headerBoxView];
    [self.headerBoxView addSubview:self.headerImageView];
    [self.topBox addSubview:self.priceLabel];
    [self.topBox addSubview:self.selectOptionsLabel];
    [self.topBox addSubview:self.closeButton];
    [self.contentView addSubview:self.optionsCollectionView];
    [self.contentView addSubview:self.sureButton];
    [self zq_addConstraints];
}

- (void)zq_addConstraints
{
    WEAKSELF
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
     }];
    
    ZQBaseBoxView *hiddenView = [ZQViewManager creatBoxView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    [hiddenView addGestureRecognizer:tap];
    [self.bgView addSubview:hiddenView];
    [hiddenView mas_makeConstraints:^(MASConstraintMaker *make)
    {
        make.left.top.right.equalTo(weakSelf.bgView);
        make.height.mas_equalTo(SCREEN_HEIGHT - 445);
    }];
    
    self.contentView.frame = CGRectMake(0, SCREEN_HEIGHT + 20, SCREEN_WIDTH, 445);
    [self.topBox mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.top.right.equalTo(weakSelf.contentView);
         make.height.mas_equalTo(95);
     }];
    
    [self.headerBoxView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(weakSelf.topBox).offset(15);
         make.top.equalTo(weakSelf.topBox).offset(-20);
         make.width.height.mas_equalTo(100);
     }];
    
    [self.headerImageView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.edges.mas_equalTo(UIEdgeInsetsMake(5, 5, 5, 5));
     }];
    
    ZQBaseView *auxiliaryLine = [[ZQBaseView alloc] initWithFrame:CGRectZero];
    auxiliaryLine.backgroundColor = COLOR_CLEAR;
    [self.topBox addSubview:auxiliaryLine];
    [auxiliaryLine mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.right.equalTo(weakSelf.topBox);
         make.centerY.equalTo(weakSelf.topBox.mas_centerY);
         make.height.mas_equalTo(2);
     }];
    
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(weakSelf.headerBoxView.mas_right).offset(15);
         make.bottom.equalTo(auxiliaryLine.mas_top).offset(-14);
     }];
    
    [self.selectOptionsLabel mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.equalTo(weakSelf.priceLabel);
         make.top.equalTo(auxiliaryLine.mas_bottom).offset(14);
     }];
    
    [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.right.equalTo(weakSelf.topBox).offset(-15);
         make.top.equalTo(weakSelf.topBox).offset(15);
         make.width.height.mas_equalTo(25);
     }];
    
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.right.bottom.equalTo(weakSelf.contentView);
         make.height.mas_equalTo(ZQTabBarHeight);
     }];
    
    [self.optionsCollectionView mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.left.right.equalTo(weakSelf.contentView);
         make.top.equalTo(weakSelf.topBox.mas_bottom);
         make.bottom.equalTo(weakSelf.sureButton.mas_top);
     }];
}

- (void)setUIData
{
    [self.headerImageView yy_setImageWithURL:[NSURL URLWithString:_goodsInfo.Pic] placeholder:nil];
    self.priceLabel.text = [NSString stringWithFormat:@"￥%.lf", _goodsInfo.Price];
    self.selectOptionsLabel.text = [NSString stringWithFormat:@"已选："];
}

+ (void)showWithGoods:(ZQGoodsModel *)goodsInfo selectOptions:(void(^)(NSDictionary *options))selectOptions
{
    ZQGoodsOptionView *view = [[ZQGoodsOptionView alloc] initWithGoodsInfo:goodsInfo options:goodsInfo.Options];
    view.optionsBlock = selectOptions;
    [view show];
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.options.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSDictionary *option = self.options[section];
    NSArray *optionData = option[@"Data"];
    return optionData.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZQBaseCollectionViewLabelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZQGoodsOptionsLableCell" forIndexPath:indexPath];
    NSDictionary *option = self.options[indexPath.section];
    NSArray *optionData = option[@"Data"];
    NSString *key = option[@"Name"];
    NSString *value = optionData[indexPath.row];
    cell.titleLabel.text = value;
    
    NSString *selectValue = self.selectOptions[key];
    if (![NSString syj_isEmptyString:selectValue] && [selectValue isEqualToString:value])
    {
        cell.titleLabel.textColor = COLOR_WHITE;
        cell.titleLabel.backgroundColor = COLOR_THEME_BEGIN;
    }
    else
    {
        cell.titleLabel.textColor = COLOR_MIDDLE;
        cell.titleLabel.backgroundColor = COLOR_HEIGH_LIGHT_THIN;
    }
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    SearchHistoryCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([SearchHistoryCollectionReusableView class]) forIndexPath:indexPath];
    NSDictionary *option = self.options[indexPath.section];
    view.titleLabel.text = option[@"Name"];
    view.titleLabel.font = [UIFont systemFontOfSize:15];
    view.showActionButton = NO;
    view.titleLabel.textColor = COLOR_DARK;
    return view;
}

#pragma mark -- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = 0;
    NSDictionary *option = self.options[indexPath.section];
    NSArray *optionData = option[@"Data"];
    NSString *value = optionData[indexPath.row];
    width = [value syj_getSizeWithFont:[UIFont systemFontOfSize:15] constraintSize:CGSizeMake(MAXFLOAT, 30)].width + 20;
    if (width >= 150)
    {
        width = 150;
    }
    return CGSizeMake(width, 30);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 30;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(collectionView.frame.size.width - 20, 40);
}

#pragma mark -- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *option = self.options[indexPath.section];
    NSArray *optionData = option[@"Data"];
    NSString *key = option[@"Name"];
    NSString *value = optionData[indexPath.row];
    [self.selectOptions setObject:value forKey:key];
    NSArray *valueArray = self.selectOptions.allValues;
    NSString *optionStr = @"#";
    for (NSString *str in valueArray)
    {
        optionStr = [NSString stringWithFormat:@"%@\"%@\" ", optionStr, str];
    }
    self.selectOptionsLabel.text = [NSString stringWithFormat:@"已选：%@", [optionStr substringFromIndex:1]];
    [collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
}

- (void)dealloc
{
    NSLog(@"释放完毕");
}

#pragma mark -- Actions
- (void)show
{
    WEAKSELF
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:1 initialSpringVelocity:5 options:0 animations:^{
        weakSelf.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
        weakSelf.contentView.frame = CGRectMake(0, SCREEN_HEIGHT - 445, SCREEN_WIDTH, 445);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)dismiss
{
    WEAKSELF
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:1 initialSpringVelocity:5 options:0 animations:^{
        weakSelf.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        weakSelf.contentView.frame = CGRectMake(0, SCREEN_HEIGHT + 20, SCREEN_WIDTH, 445);
    } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
}

- (void)goPayAction:(UIButton *)sender
{
    if (self.selectOptions.allKeys.count < self.options.count)
    {
        CPAlertView *alert = [CPAlertView alertWithMessage:@"请选择商品类型" items:nil];
        alert.rectCorner = UIRectCornerAllCorners;
        [alert show];
    }
    else
    {
        [self dismiss];
        if (self.optionsBlock)
        {
            self.optionsBlock(self.selectOptions);
        }
    }
}

#pragma mark -- ViewLazyLoad;
- (ZQBaseBoxView *)bgView
{
    if (!_bgView)
    {
        _bgView = [[ZQBaseBoxView alloc] initWithFrame:CGRectZero];
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    }
    return _bgView;
}

- (ZQBaseBoxView *)contentView
{
    if (!_contentView)
    {
        _contentView = [[ZQBaseBoxView alloc] initWithFrame:CGRectZero];
        _contentView.backgroundColor = COLOR_WHITE;
    }
    return _contentView;
}

- (ZQBaseBoxView *)topBox
{
    if (!_topBox)
    {
        _topBox = [ZQViewManager creatBoxView];
    }
    return _topBox;
}

- (ZQBaseBoxView *)headerBoxView
{
    if (!_headerBoxView)
    {
        _headerBoxView = [[ZQBaseBoxView alloc] initWithFrame:CGRectZero];
        _headerBoxView.backgroundColor = COLOR_WHITE;
        _headerBoxView.layer.cornerRadius = 5.f;
        _headerBoxView.layer.borderColor = COLOR_THIN.CGColor;
        _headerBoxView.layer.borderWidth = ZQBoderLineSize;
    }
    return _headerBoxView;
}

- (UIImageView *)headerImageView
{
    if (!_headerImageView)
    {
        _headerImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        _headerImageView.contentMode = UIViewContentModeScaleAspectFit;
        _headerImageView.canSeeDetail();
    }
    return _headerImageView;
}

- (ZQBaseLabel *)priceLabel
{
    if (!_priceLabel)
    {
        _priceLabel = [ZQViewManager creatLabel];
        _priceLabel.textColor = COLOR_THEME_BEGIN;
        _priceLabel.font = [UIFont systemFontOfSize:13];
        _priceLabel.numberOfLines = 1;
    }
    return _priceLabel;
}

- (ZQBaseLabel *)selectOptionsLabel
{
    if (!_selectOptionsLabel)
    {
        _selectOptionsLabel = [ZQViewManager creatLabel];
        _selectOptionsLabel.textColor = COLOR_DARK;
        _selectOptionsLabel.font = [UIFont systemFontOfSize:14];
    }
    return _selectOptionsLabel;
}

- (UIButton *)closeButton
{
    if (!_closeButton)
    {
        _closeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_closeButton setImage:IMAGENAMED(GOODS_OPTION_CLOSE) forState:(UIControlStateNormal)];
        [_closeButton setTitleColor:COLOR_DARK forState:(UIControlStateNormal)];
        _closeButton.backgroundColor = COLOR_WHITE;
        [_closeButton addTarget:self action:@selector(dismiss) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _closeButton;
}

- (UICollectionView *)optionsCollectionView
{
    if (!_optionsCollectionView)
    {
        _optionsCollectionView = [ZQViewManager creatUICollectionViewWithSlidingDirection:(UICollectionViewScrollDirectionVertical)];
        UICollectionViewLeftAlignedLayout *layout = [[UICollectionViewLeftAlignedLayout alloc] init];
        [_optionsCollectionView setCollectionViewLayout:layout];
        _optionsCollectionView.delegate = self;
        _optionsCollectionView.dataSource = self;
        [_optionsCollectionView registerClass:[ZQBaseCollectionViewLabelCell class] forCellWithReuseIdentifier:@"ZQGoodsOptionsLableCell"];
        [_optionsCollectionView registerClass:[SearchHistoryCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([SearchHistoryCollectionReusableView class])];
    }
    return _optionsCollectionView;
}

- (UIButton *)sureButton
{
    if (!_sureButton)
    {
        _sureButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_sureButton setTitle:@"确定" forState:(UIControlStateNormal)];
        [_sureButton setTitleColor:COLOR_WHITE forState:(UIControlStateNormal)];
        _sureButton.backgroundColor = COLOR_THEME_BEGIN;
        [_sureButton addTarget:self action:@selector(goPayAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _sureButton;
}

- (NSMutableDictionary *)selectOptions
{
    if (!_selectOptions)
    {
        _selectOptions = [NSMutableDictionary dictionary];
    }
    return _selectOptions;
}

@end
